const PENDING = 1;
const FULFILLED = 2;
const REJECTED = 3;

// 核心 .then().then().then()
// 每个.then() 都是返回一个新的对象
class Promise {
  constructor(executor) {
    this.state = PENDING;
    this.fulfills = [];
    const resolver = (value) => {
      if (this.state === PENDING) {
        this.state = FULFILLED;
        this.value = value;
        for (const [onfulfill, resolve] of this.fulfills) {
          const x = onfulfill(this.value);
          resolve(x);
        }
      }
    };
    const rejector = (error) => {};

    executor(resolver, rejector);
  }

  then(onFulfill) {
    return new Promise((resolve, reject) => {
      switch (this.state) {
        case PENDING:
          this.fulfills.push([onFulfill, resolve]);
          break;
        case FULFILLED:
          const x = onFulfill(this.value);
          resolve(x);
          break;
      }
    });
  }
}

const p = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve(10);
  }, 100);
})
  .then((res) => {
    console.log(res);
    return "abc";
  })
  .then((res) => {
    console.log(res);
  });
